import typing

from fastapi import APIRouter, Header
from pydantic import BaseModel

from DataModels.database import User
from DataModels.share import RespInfo, RespResultCode, StatusInfo
from DataModels.user import SexEnum
from utils.token import check_token
from utils.user import user_to_user_info


class UpdateRequest(BaseModel):
    nick: typing.Optional[str]
    avatar: typing.Optional[str]
    sex: typing.Optional[SexEnum]
    birthday: typing.Optional[int]
    openid: typing.Optional[str]


# => response
# {info: UserInfo}

update_router = APIRouter(prefix="/update")


@update_router.post("")
async def update(data: UpdateRequest, token=Header(None)):
    if token is None:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.TokenEmpty,
                msg="未授权的请求",
            )
        )
    ok, info = check_token(token)
    if not ok:
        return info
    token = info
    phone = token.phone  # type: ignore
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="未找到手机号",
            )
        )
    if data.nick is not None:
        user.nick = data.nick
    if data.avatar is not None:
        user.avatar = data.avatar
    if data.sex is not None:
        user.sex = data.sex
    if data.birthday is not None:
        user.birthday = data.birthday
    if data.openid is not None:
        user.openid = data.openid
    await user.save()  # type: ignore

    user_info = user_to_user_info(user)
    return RespInfo(
        info=user_info,
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="更新成功",
        ),
    )
